package QQServe;

import Common.Message;
import Common.MessageType;
import Common.User;

import java.awt.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class QQServe {
    private ServerSocket ss = null;
    private static HashMap<String,User> validUser=new HashMap<String,User>();
    //初始化用户数据
    static {
        validUser.put("1", new User("1", "1"));
        validUser.put("2", new User("2", "2"));
        validUser.put("3", new User("3", "3"));
    }
    public QQServe() {
        try {
            System.out.println("9999监听");
            ss = new ServerSocket(9999);

            while (true) {
                Socket socket = ss.accept();
                //一直监听
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                User user = (User) ois.readObject();
                //检验客户端用户密码
                if (checkUser(user.getUserId(), user.getPassword())){
                    System.out.println("用户"+user.getUserId()+"校验成功");
                   //创建对象回复客户端
                    Message message=new Message();
                    message.setMsgType(MessageType.MESSAGE_LOGIN_SUCCEED);
                    ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject(message);
                    //创建线程 服务端连接客户端
                    ServeConnectClientThread thread=new ServeConnectClientThread(socket, user.getUserId());
                    thread.start();
                    ManageClientThread.addThread(user.getUserId(), thread);

                }else {
                    System.out.println("验证失败");
                    Message message=new Message();
                    message.setMsgType(MessageType.MESSAGE_LOGIN_FAIL);
                    ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject(message);
                    socket.close();
                }

            }

        } catch (Exception e) {
            e.getMessage();
        }
    }
    public boolean checkUser(String userId,String password){
        User user=validUser.get(userId);
        if (user==null){
            System.out.println("不存在");
            return false;
        }if (!user.getPassword().equals(password)){
            System.out.println("密码错误");
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        new QQServe();
    }
}
